package com.csust.automaticteach.app.teacher;

import cn.hutool.json.JSONUtil;
import com.csust.automaticteach.app.advisor.MyLoggerAdvisor;
import com.csust.automaticteach.model.dto.generateexam.AddGenerateExamForAiRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Component;

import static com.csust.automaticteach.constant.AppPromptConstant.EXAM_SYSTEM_ROLE;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @ClassNameExerciseGenerateAndEvaluateApp
 * @Description 练习生成与评测助手
 * @Author钰玟
 * @Date2025/6/20 上午9:12
 * @Version 1.0
 **/
@Component
@Slf4j
public class ExamGenerateApp {
    private ChatClient chatClient;


    public ExamGenerateApp(ChatModel dashscopeChatModel) {
        //基于内存的会话记忆存储
        ChatMemory chatMemory = new InMemoryChatMemory();
        this.chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(EXAM_SYSTEM_ROLE)//系统预设
                .defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory),//会话记忆存储
                        new MyLoggerAdvisor())//日志记录
                .build();
    }

    /**
     * 支持多轮对话记忆的 聊天
     *
     * @param addGenerateExamForAiRequest 用户的问题
     * @param chatId                      会话id
     * @return
     */
    public String doGenerate(AddGenerateExamForAiRequest addGenerateExamForAiRequest, String chatId) {
        String jsonStr = JSONUtil.toJsonStr(addGenerateExamForAiRequest);
        ChatResponse chatResponse = chatClient.prompt()
                .user(jsonStr)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(
                        CHAT_MEMORY_RETRIEVE_SIZE_KEY, 5))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }
}
